<?php

//------------------------
// 角色组管理控制器
//-------------------------
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\AdminUser as AdminUserModel;
use app\common\model\AuthGroup as AuthGroupModel;
use app\common\model\AuthGroupAccess as AuthGroupAccessModel;
use think\Db;

class AuthGroup extends AdminBase
{
    protected $AdminUserModel;
    protected $AuthGroupModel;
    protected $AuthGroupAccessModel;

    protected function _initialize()
    {
        parent::_initialize();
        $this->AdminUserModel        = new AdminUserModel();
        $this->AuthGroupModel        = new AuthGroupModel();
        $this->AuthGroupAccessModel  = new AuthGroupAccessModel();
    }

    // 认证规则列表
    public function index(){
        $title       = $this->request->param('title','','trim');
        $status      = $this->request->param('status',0,'intval');
        $is_delete   = $this->request->param('is_delete',0,'intval');

        $where = array();
        if ($status) {
            $_status = $status == 2?0:1;
            $where['status'] = array('eq',$_status);
        }
        if ($is_delete) {
            $_is_delete = $is_delete == 2?0:1;
            $where['is_delete'] = array('eq',$_is_delete);
        }
        if ($title) {
             $where['title'] = array('like','%'.$title.'%');
        }

        $info = $this->AuthGroupModel->where($where)->
        paginate(10,false,['query' => [
            'status'    =>$status,
            'is_delete' =>$is_delete,
            'title'     =>$title
            ] ]);

        $this->assign('info',$info);
        $this->assign('title',$title);
        $this->assign('status',$status);
        $this->assign('is_delete',$is_delete);
        return $this->fetch('index');
    }

    // 添加页面
    public function add(){
        return $this->fetch('add');
    }

    // 编辑页面
    public function edit(){
        $id = $this->request->param('id',0,'intval');

        $data = $this->AuthGroupModel->get($id);

        $this->assign('data',$data);

        return $this->fetch('edit');
    }

    /**
     * @desc 添加/编辑操作
     */
    public function addProc() {

        $data = $this->request->param();
        $id   = $this->request->param('id',0,'intval');

        if ($id) {
            // 编辑
            $data['id'] = $id;
            $validate_result = $this->validate($data, 'AuthGroup.edit');
            if ($validate_result !== true) {
                $this->error($validate_result);
            }
            $res = $this->AuthGroupModel->allowField(true)->save($data,$id);
            $act = "编辑";
        } else {
            // 添加
            $validate_result = $this->validate($data, 'AuthGroup.add');
            if ($validate_result !== true) {
                $this->error($validate_result);
            }
            $act = "添加";
            $res = $this->AuthGroupModel->allowField(true)->save($data);
        }

        if ($res === false) {
            $this->error($this->AuthGroupModel->getError());
        } else {
            $this->success('用户组'.$act.'成功');
        }
    }

    // 删除操作
    public function delete(){
        $id = $this->request->param('id',0,'intval');

        $where['is_delete'] = array('eq',1);
        $where['id'] = array('eq',$id);
        $res = $this->AuthGroupModel->where($where)->delete();

        if ($res === false) {
            $this->error($this->AuthGroupModel->getError());
        } else{
            // 删除成功后，才删除中间表的数据
            if ($res != 0) {
                $this->AuthGroupAccessModel->where('group_id',$id)->delete();
                $this->success('删除成功');
            } else {
                $this->error('该用户组不能删除');
            }
        }
    }

    // 批量删除用户组>>调用
    private function _batchDelete($id){
        $where['is_delete'] = array('eq',1);
        $where['id'] = array('eq',$id);
        $res = $this->AuthGroupModel->where($where)->delete();

        if ($res == false) {
           return false;
        } else {
            $this->AuthGroupAccessModel->where('group_id',$id)->delete();
            return true;
        }

    }

     // 批量处理
    public function batchProc(){
        $data = $this->request->param();

        $ids = implode(',',$data['ids']);
        $map['id']  = ['in',$ids];
        $type = $data['type'];

        switch ($type) {
            case 'delete':
                $successData = array();
                $failData = array();
                for ($i=0; $i < count($data['ids']); $i++) { 
                    $result = $this->_batchDelete($data['ids'][$i]);
                    if ($result) {
                        array_push($successData, $data['ids'][$i]);
                    } else {
                        array_push($failData, $data['ids'][$i]);
                    }
                }
                $success = implode(',',$successData);
                $fail   = implode(',',$failData);
                $this->success('删除成功id为：'.$success.'，删除失败id为：'.$fail);
                break;
            case 'disable':
                $res = $this->AuthGroupModel->where($map)->update(['status' => '0']);
                $act = '禁用';
                break;
            case 'enable':
                $res = $this->AuthGroupModel->where($map)->update(['status' => '1']);
                $act = '启用';
                break;

            default:
                $this->error('非法操作');
                break;
        }
        if ($res === false) {
            $this->error($this->AuthGroupModel->getError());
            // 记录日志
        } else {
            $this->success('批量'.$act.'成功');
        }

    }

    // 设置用户组规则
    public function setAuth(){
        $id = $this->request->param('id',0,'intval');

        $rules = $this->AuthGroupModel->get($id)->rules;

        $rules_array = explode(',',$rules);

        $is_auth = array();
        foreach ($rules_array as $k => $v) {
            $is_auth[$v] = true;
        }

        $model = Db::name('AuthRule');

        $parent = $model->where(array('pid'=>0))->select()->toArray();

        for ($i=0; $i < count($parent); $i++) { 
            $child = array();
            $child = $model->where(array('pid' => $parent[$i]['id']))->select()->toArray();
            $parent[$i]['child'] = $child;
        }

        $this->assign('id',$id);
        $this->assign('is_auth',$is_auth);
        $this->assign('parent',$parent);

        return $this->fetch('set_auth_page');

    }

    // 保存用户组规则
    public function saveAuth(){
        $info    = $this->request->param('');
        $id      = $info['id'];
        $auths   = isset($info['auth_id'])?$info['auth_id']:array();

        $auths = implode(",", $auths);

        $data = array(
            'id' => $id,
            'rules' => $auths,
        );

        $res = $this->AuthGroupModel->isUpdate(true)->save($data,$data['id']);

        if ($res === false) {
            $this->error($this->AuthGroupModel->getError());
        } else {
            $this->success('保存成功');
        }
    }

    //  设置用户组用户页面
    public function setUser(){
        $id = $this->request->param('id',0,'intval');
        $username = $this->request->param('username','','trim');

        $AuthGroupAccessModel = Db::name('AuthGroupAccess');

        $is_user = $AuthGroupAccessModel->where('group_id',$id)->field('uid')->select();

        // 已设置的用户
        $is_user = two_to_one($is_user,'uid');

        $where = array();
        $where['status'] = array('EQ',1);

        if ($username) {
             $where['username'] = array('like','%'.$username.'%');
        }

        $info = $this->AdminUserModel->where($where)->
        paginate(10,false,['query' => [
            'username' => $username
            ] ]);

        $this->assign('id',$id);
        $this->assign('username',$username);
        $this->assign('is_user',$is_user);
        $this->assign('info',$info);

        return $this->fetch('set_user_page');
    }

    // 保存用户组用户
    public function saveUser(){
        $info    = $this->request->param('');
        $id      = $info['id'];
        $users   = isset($info['user_id'])?$info['user_id']:array();


        if ($users) {
            // 先删除$id相关的所有数据
            $this->AuthGroupAccessModel->where('group_id',$id)->delete();
            // 循环添加$users数组中的相关用户到$id 用户组中
            $data = [];
            foreach ($users as $value) {
                $data[] = [
                    'group_id' => $id,
                    'uid'      => $value
                ];
            }
            $res = $this->AuthGroupAccessModel->saveAll($data);
        } else {
            $res = $this->AuthGroupAccessModel->where('group_id',$id)->delete();
        }

        if ($res) {
            $this->success('保存成功');
        } else {
            $this->error($this->AuthGroupModel->getError());
        }
    }



}